package com.example.demo.controller;

import com.example.demo.api.CommonResult;
import com.example.demo.api.ResultCode;
import com.example.demo.entity.User;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/house/v1")
public class UserController {

    @Autowired
    private UserService userservice;
    @Autowired
    private TokenService tokenservice;

    /**
     * 注册操作
     */
    @PostMapping("/users")
    public CommonResult register(@RequestBody User user){

        System.out.println(user+"......注册......");

        try {
            userservice.insertAUsers(user);/**数据库中插入用户信息**/
            /**注册成功**/
            System.out.println("注册成功\n");
            return CommonResult.result(ResultCode.REGISTER_SUCCESS.getCode(), ResultCode.REGISTER_SUCCESS.getMessage());
        } catch (DuplicateKeyException e) {/**用户已存在**/
            System.out.println("用户已存在\n");
            return CommonResult.result(ResultCode.REGISTER_USER_FAILED.getCode(), ResultCode.REGISTER_USER_FAILED.getMessage());
        }catch (Exception e) {
            System.out.println(e.toString()+"\n注册失败\n");
            return CommonResult.result(ResultCode.REGISTER_FAILED.getCode(), ResultCode.REGISTER_FAILED.getMessage());
        }
    }

    /**
     * 注销操作
     */
    @DeleteMapping("/users/{username}/{token}")
    public CommonResult cellation(@PathVariable(name="token") String token,
                                  @PathVariable(name="username") String username){
        System.out.println("username: "+tokenservice.getName(token)+"......注销......");
        try {
            if (tokenservice.searchToken(token)&&username.equals(tokenservice.getName(token))) {
                userservice.deleteAUsers(tokenservice.getName(token));/**从数据库中删除用户**/
                tokenservice.deleteToken(token);/**删除登录的token**/

                /**注销成功**/
                System.out.println("注销成功"+"..\n");
                return CommonResult.result(ResultCode.CANCEL_SUCCESS.getCode(), ResultCode.CANCEL_SUCCESS.getMessage());
            } else {
                /**非法用户**/
                System.out.println("非法用户\n");
                return CommonResult.result(ResultCode.TOKEN_FAILED.getCode(), ResultCode.TOKEN_FAILED.getMessage());
            }
        } catch (Exception e) {/**注销失败**/
            System.out.println(e.toString()+"\n注销失败\n");
            return CommonResult.result(ResultCode.CANCEL_FAILED.getCode(), ResultCode.CANCEL_FAILED.getMessage());
        }
    }

    /**
     * 登录操作
     */
    @PostMapping("/users/login")//登录
    public CommonResult login(@RequestBody User user){

        System.out.println("......登录......");
        try {
            User temp = userservice.findAUsers(user.getUsername());
            //System.out.println(temp);
            if(temp.getPassword().equals(user.getPassword())) {
                if(temp.getBanned()) {/**用户被封禁**/
                    System.out.println("用户被封禁\n");
                    return CommonResult.result(ResultCode.BANNED_FAILED.getCode(), ResultCode.BANNED_FAILED.getMessage());
                } else if(temp.getAdmin()) {/**管理员登录**/
                    String token = tokenservice.createToken();
                    tokenservice.putToken(user.getUsername(), token);
                    System.out.println("管理员登录成功\n");
                    return CommonResult.result(ResultCode.A_LOGIN_SUCCESS.getCode(), ResultCode.A_LOGIN_SUCCESS.getMessage(), token);
                } else {/**普通用户登录**/
                    String token = tokenservice.createToken();
                    tokenservice.putToken(user.getUsername(), token);
                    System.out.println("登录成功\n");
                    return  CommonResult.result(ResultCode.U_LOGIN_SUCCESS.getCode(), ResultCode.U_LOGIN_SUCCESS.getMessage(), token);
                }
            } else{/**密码错误**/
                System.out.println("密码错误\n");
                return CommonResult.result(ResultCode.PASSWORD_FAILED.getCode(), ResultCode.PASSWORD_FAILED.getMessage());
            }
        } catch(NullPointerException e) {/**用户不存在**/
            System.out.println("用户不存在\n");
            return CommonResult.result(ResultCode.USERNAME_FAILED.getCode(), ResultCode.USERNAME_FAILED.getMessage());
        } catch (Exception e){
            System.out.println(e.toString()+"\n登陆失败\n");
            return CommonResult.result(ResultCode.LOGIN_FAILED.getCode(), ResultCode.LOGIN_FAILED.getMessage());}
        
    }

    /**
     * 退出登录
     */
    @DeleteMapping("/users/log/{username}/{token}")
    public CommonResult logout(@PathVariable(name="token") String token,
                               @PathVariable(name="username") String username) {
        System.out.println("token: "+token+" , username"+tokenservice.getName(token)+" 退出......");
        try {
            if (tokenservice.searchToken(token)&&username.equals(tokenservice.getName(token))) {
                tokenservice.deleteToken(token);
                /**退出成功**/
                System.out.println("退出成功\n");
                return CommonResult.result(ResultCode.LOGOUT_SUCCESS.getCode(), ResultCode.LOGOUT_SUCCESS.getMessage());
            } else {
                /**非法用户**/
                System.out.println("非法用户\n");
                return CommonResult.result(ResultCode.TOKEN_FAILED.getCode(), ResultCode.TOKEN_FAILED.getMessage());
            }
        } catch (Exception e) {/**退出失败**/
            System.out.println(e.toString()+"\n退出失败\n");
            return CommonResult.result(ResultCode.LOGOUT_FAILED.getCode(), ResultCode.LOGOUT_FAILED.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/user/{username}/{token}")
    public CommonResult changePWD(@PathVariable(name="token") String token,
                                  @PathVariable(name="username") String username,
                                  @RequestBody String pwd){
        System.out.println("......修改密码.....");
        try {
            if (tokenservice.searchToken(token)&&username.equals(tokenservice.getName(token))) {
                userservice.changePWD(username, pwd);

                System.out.println("修改成功"+"..\n");
                return CommonResult.result(ResultCode.CANCEL_SUCCESS.getCode(), ResultCode.CANCEL_SUCCESS.getMessage());
            } else {
                /**非法用户**/
                System.out.println("非法用户\n");
                return CommonResult.result(ResultCode.TOKEN_FAILED.getCode(), ResultCode.TOKEN_FAILED.getMessage());
            }
        } catch (Exception e) {
            System.out.println(e.toString()+"\n修改失败\n");
            return CommonResult.result(ResultCode.CANCEL_FAILED.getCode(), ResultCode.CANCEL_FAILED.getMessage());
        }
    }


}